<?php

namespace App\Http\Controllers\Firm;

use App\Events\Rank;
use App\Events\Share;
use App\Http\Controllers\BaseController;
use App\Models\Firm;
use App\Models\FirmNotInterested;
use App\Rules\Code;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class FirmController extends BaseController
{

    public function index(Request $request)
    {
        $param = $this->validate($request,[
            'profession_id' => 'integer',
            'category_id' => 'integer',
            'keyword' => 'string',
            'cooperation_area' => 'max:60',
            'order_type' =>  'in:form,comment,view,',
            'rank_type' => 'in:1,2,3,4,5,6,7',
            'start_invest_amount' => 'numeric',
            'end_invest_amount' => 'numeric',
            'is_cooperation' => 'in:1,2'
        ]);

        $query = Firm::query()
                    ->selectRaw('*,(select count(view_count) from firm_browses where firm_id=firms.id) as view_count,
                    (select count(id) from firm_messages where firm_id=firms.id) as join_count,
                      (select count(id) from user_like_firms where firm_id=firms.id) as like_count,
                    (select count(user_id) from user_follows where status=1 and friend_id=firms.user_id) as follow_count,
                     (select count(id) from user_collect_firms where status=1 and firm_id=firms.id) as collect_count,
                     (select sum(share_count) from user_share_firms where firm_id=firms.id) as share_count,
                      (select count(id) from firm_comments where audit_status=2 and firm_id=firms.id) as comment_count,
                      (select count(user_id) from firm_consultations where firm_id=firms.id) as consultation_count')
                    ->with('profile')
                    ->whereNotExists(function ($q){
                        $user_id = auth('api')->id();
                        $q->select(DB::raw(1))
                            ->from('firm_not_interesteds')
                            ->where('user_id',$user_id)
                            ->whereColumn('firm_not_interesteds.firm_id','firms.id');
                    });

        if (isset($param['cooperation_area'])){
            $cooperation_area = $param['cooperation_area'];
            $query->whereHas('profile',function ($q) use ($cooperation_area){
                $q->where('cooperation_area','like','%'.$cooperation_area.'%');
            });
        }

        if (isset($param['rank_type'])){
            switch ($param['rank_type']){
                case 1 :
                    $query->orderByDesc('view_count');
                    break;
                case 2 :
                    $query->orderByDesc('like_count');
                    break;
                case 3 :
                    $query->orderByDesc('follow_count');
                    break;
                case 4 :
                    $query->orderByDesc('join_count');
                    break;
                case 5 :
                    $query->orderByDesc('collect_count');
                    break;
                case 6 :
                    $query->orderByDesc('share_count');
                    break;
                case 7 :
                    $query->orderByDesc('comment_count');
                    break;
            }
        }else{

            $query->orderByDesc('id');
        }


        if (isset($param['category_id'])){
            $query->where('category_id',$param['category_id']);
        }

        if (isset($param['is_cooperation'])){
            $query->where('is_cooperation',$param['is_cooperation']);
        }

        if (isset($param['profession_id'])){
            $query->where('profession_id',$param['profession_id']);
        }


        if (isset($param['start_invest_amount']) && isset($param['end_invest_amount'])){
            $start_invest_amount = $param['start_invest_amount'];
            $end_invest_amount = $param['end_invest_amount'];
            $query->whereHas('profile',function ($q) use ($start_invest_amount,$end_invest_amount){
                $q->whereBetween('invest_amount',[$start_invest_amount,$end_invest_amount]);
            });
        }


        if (isset($param['keyword'])){
            $query->where('name','like','%'.$param['keyword'].'%');
        }



        $profiles = $query->simplePaginate();

        return $this->success($profiles);
    }


    public function interested(Request $request)
    {
        $param = $this->validate($request,[
            'firm_id' => 'required|integer'
        ]);
        $param['user_id'] = auth('api')->id();
        $model =  FirmNotInterested::query()->create($param);

        if ($model->getKey()){
            return $this->success('请求成功');
        }
        return $this->success('请求失败');
    }


    public function share(Request $request)
    {
        $param = $this->validate($request,[
            'firm_id' => 'required|integer'
        ]);

        $user_id = auth('api')->id();
        $share_id  = DB::table('user_share_firms')
            ->where('user_id',$user_id)
            ->where('firm_id',$param['firm_id'])
            ->whereDate('share_time',date('Y-m-d'))
            ->value('id');

        if (!$share_id){
            $result = DB::table('user_share_firms')->insert([
                'user_id' => $user_id,
                'firm_id' => $param['firm_id'],
                'share_count' => 1,
                'share_time' => date('Y-m-d H:i:s')
            ]);
        }else{
            $result = DB::table('user_share_firms')
                ->where('id',$share_id)
                ->increment('firm_id');
        }

        event(new Share($user_id));

        return $result ? $this->success() : $this->error();
    }

    public function show(Request $request)
    {
        $param = $this->validate($request,[
            'firm_id' => 'integer',
            'user_id' => 'integer'
        ]);

        $user_id = auth('api')->id();

        $query = Firm::query()
                 ->selectRaw('*,(select count(friend_id) from user_follows where status=1 and friend_id=firms.user_id and user_id='.$user_id.') as is_follow,(select count(id) from user_collect_firms where firm_id=firms.id and status=1 and user_id='.$user_id.') as is_collect,(select count(id) from user_like_firms where firm_id=firms.id and status=1 and user_id='.$user_id.') as is_like,
                        (select count(id) from user_like_firms where firm_id=firms.id) as like_count,
                        (select count(id) from firm_messages where firm_id=firms.id) as join_count,
                        (select sum(view_count) from firm_browses where firm_id=firms.id) as view_count,
                    (select count(user_id) from user_follows where status=1 and friend_id=firms.user_id) as follow_count,
                     (select count(user_id) from firm_consultations where firm_id=firms.id) as consultation_count')
                ->with(['brands' => ['profile'],'profile','gift' => function($q){
                    $q->with('user:id,avatar,nickname')->where('status',1)->limit(10);
                }])->withCount(['gift' => function($q1){
                    $q1->where('status',1);
                }]);
        if (isset($param['firm_id'])){

            $query->where('id',$param['firm_id']);

            $browse_id =  DB::table('firm_browses')
                ->whereDate('view_time',date('Y-m-d'))
                ->where('user_id',$user_id)
                ->where('firm_id',$param['firm_id'])
                ->value('id');

            if (!$browse_id){
                DB::table('firm_browses')
                    ->insert([
                        'firm_id' => $param['firm_id'],
                        'user_id' => $user_id,
                        'view_count' => 1,
                        'view_time' => date('Y-m-d H:i:s')
                    ]);
            }else{
                DB::table('firm_browses')->where('id',$browse_id)->increment('view_count');
            }

        }


        if (isset($param['user_id'])){
            $query->where('user_id', $param['user_id']);
        }

        if (!isset($param['user_id']) && !isset($param['firm_id'])){
            $query->where('user_id', auth('api')->id());
        }

        $firm = $query->first();

        return $this->success($firm ?? []);
    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
               'profession_id' => 'required|integer',
               'category_id' => 'required|integer',
               'name' => 'required',
               'area' => 'required',
               'corporate_name' => 'required',
               'idcard_reverse_photo' => 'required',
               'idcard_front_photo' => 'required',
               'business_license' => 'required',
               'corporate_phone' => 'required',
               'brands.*.name' => 'required',
               'brands.*.firm_profession_id' => 'required',
               'brands.*.brand_cradle_id' => 'required',
               'brands.*.brand_location_id' => 'required',
               'brands.*.certificate' => 'string',
               'code' => ['required',new Code()]
        ]);


        $param['user_id'] = auth('api')->id();

        $firm =  Firm::query()->where('user_id',$param['user_id'])->first();

        if (empty($firm)){
            $firm = Firm::query()->create($param);

            if (isset($param['brands'])){
                $firm->brands()->createMany($param['brands']);
            }

            if ($firm->getKey()){
                event(new \App\Events\Firm($param['user_id']));
                return $this->success('申请成功');
            }
        }else{

            $brands = $param['brands'] ?? null;
            unset($param['brands'],$param['code']);
            $param['audit_status'] = 1;
            $rows = Firm::query()->where('id',$firm->getKey())->update($param);

            if ($brands){
                DB::table('firm_brands')->where('firm_id',$firm->getKey())->delete();
                $firm->brands()->createMany($brands);
            }

            if ($rows){
                return $this->success('申请成功');
            }
        }


        return  $this->error('申请失败');

    }


    public function consultation(Request $request)
    {
        $params = $this->validate($request,[
            'firm_id' => 'required|integer'
        ]);


        $params['user_id'] = auth('api')->id();

        $exists = DB::table('firm_consultations')->where($params)->exists();

        if (!$exists){
            DB::table('firm_consultations')->insert($params);
        }

        return $this->success();

    }
}
